package com.net.xpay.common.service.impl;

import com.google.common.base.Preconditions;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.helper.UploadHelper;
import com.net.common.exception.BusinessException;
import com.net.xpay.common.service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author by  on 2017/6/21.
 * 保存图片
 */
@Slf4j
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private UploadHelper uploadHelper;

    @Override
    public String saveImage(User user, MultipartFile file) {
        if (file == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件不能为空");
        }
        ensurePictureUploadParam(file, user);
        String filename = StringUtils.cleanPath(file.getOriginalFilename() == null ? "" : file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件内容不能为空");
            }
            String name = UUID.randomUUID().toString().replace("-", "") + ".jpg";

            return uploadHelper.upload(name, file.getInputStream(), LocalDateTime.now().plusYears(100L));
        } catch (BusinessException be) {
            throw be;
        } catch (Exception e) {
            log.warn("save image failed|fileName={}", filename, e);
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "上传异常,请稍后重试");
        }
    }

    @Override
    public String adminSaveImage(MultipartFile file) {
        if (file == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件不能为空");
        }
        ensurePictureUploadParam(file);
        String filename = StringUtils.cleanPath(file.getOriginalFilename() == null ? "" : file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件内容不能为空");
            }
            String name = UUID.randomUUID().toString().replace("-", "") + ".jpg";

            return uploadHelper.upload(name, file.getInputStream(), LocalDateTime.now().plusYears(100L));
        } catch (BusinessException be) {
            throw be;
        } catch (Exception e) {
            log.warn("save image failed|fileName={}", filename, e);
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "上传异常,请稍后重试");
        }
    }

    @Override
    public String commonSaveImage(String uuid, MultipartFile file) {
        if (file == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件不能为空");
        }
        ensurePictureUploadParam(file);
        String filename = StringUtils.cleanPath(file.getOriginalFilename() == null ? "" : file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件内容不能为空");
            }
            String name = uuid + ".jpg";

            return uploadHelper.upload(name, file.getInputStream(), LocalDateTime.now().plusYears(100L));
        } catch (BusinessException be) {
            throw be;
        } catch (Exception e) {
            log.warn("save image failed|fileName={}", filename, e);
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "上传异常,请稍后重试");
        }
    }


    public void ensurePictureUploadParam(MultipartFile multipartFile, User user) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            log.warn("ensurePictureUploadParam|upload Image is empty|userId={}", user.getId());
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "图片上传失败");
        }
        String fileName = multipartFile.getOriginalFilename();
        Preconditions.checkArgument(fileName != null);
        if (!(fileName.endsWith("png") || fileName.endsWith("jpg") || fileName.endsWith("jpeg") || fileName.endsWith("gif") || fileName.endsWith("JPEG") || fileName.endsWith("JPG")|| fileName.endsWith("PNG"))) {
            log.warn("upload Image file suffix error|userId={}|fileName={}", user.getId(), fileName);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "图片格式错误，只支持png、jpg、jpeg、gif格式的图片上传");
        }

        long size = multipartFile.getSize();

        if (size > 5 * 1024 * 1024L) {
            log.warn("ensurePictureUploadParam|image file is too large|fileSize={}|userId={}", size, user.getId());
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传图片最大5M");
        }
    }


    public void ensurePictureUploadParam(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            log.warn("ensurePictureUploadParam|upload Image is empty");
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "图片上传失败");
        }
        String fileName = multipartFile.getOriginalFilename();
        Preconditions.checkArgument(fileName != null);
        if (!(fileName.endsWith("png") || fileName.endsWith("jpg") || fileName.endsWith("jpeg") || fileName.endsWith("gif")
        || fileName.endsWith("PNG") || fileName.endsWith("JPG") || fileName.endsWith("JPEG") || fileName.endsWith("GIF"))) {
            log.warn("upload Image file suffix error|fileName={}", fileName);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "图片格式错误，只支持png、jpg、jpeg、gif格式的图片上传");
        }

        long size = multipartFile.getSize();

        if (size > 5 * 1024 * 1024L) {
            log.warn("ensurePictureUploadParam|image file is too large|fileSize={}", size);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传图片最大5M");
        }
    }

}